package com.hoodbrains.insideloc.shopping;

import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.hoodbrains.insideloc.R;
import com.hoodbrains.insideloc.utils.Catalog;
import com.hoodbrains.insideloc.utils.ItemHolder;

public class ShoppingListAdapter extends BaseAdapter {

	private LayoutInflater inflater;
	private OnClickListener listener;

	private ShoppingList model;
	private List<ShoppingItem> items;

	public ShoppingListAdapter(Context ctx, OnClickListener listener,
			ShoppingList model) {
		this.listener = listener;
		this.model = model;
		inflater = LayoutInflater.from(ctx);
		model.registerAdapter(this);
		this.items = model.getItemList();
	}

	@Override
	public boolean hasStableIds() {
		return true;
	}

	/**
	 * Refresh the source elements list before repaint.
	 */
	@Override
	public void notifyDataSetChanged() {
		items = model.getItemList();

		super.notifyDataSetChanged();
	}

	public View getView(int position, View convertView, ViewGroup parent) {

		if (convertView == null) {
			convertView = inflater.inflate(R.layout.shop_list_item, parent,
					false);
		}

		TextView name = (TextView) convertView.findViewById(R.id.produit_sli);
		CheckBox cbx = (CheckBox) convertView.findViewById(R.id.checkbox_sli);

		if (position == 0) {
			name.setText(R.string.add_shopping_item);
			cbx.setVisibility(View.GONE);
		} else {
			cbx.setVisibility(View.VISIBLE);

			ShoppingItem item = getItem(position - 1);
			name.setText(item.getName());
			String color = Catalog.getInstance().getColor(item.rayon);

			name.setTextColor(Color.parseColor(color));

			ItemHolder<ShoppingItem> iH = new ItemHolder<ShoppingItem>(item,
					position, -1);

			cbx.setChecked(item.grabbed);
			cbx.setEnabled(!item.isGrabbed());
			cbx.setTag(iH);
			cbx.setOnClickListener(listener);

		}
		return convertView;

	}

	public int getCount() {
		return items.size() + 1;
	}

	public ShoppingItem getItem(int position) {
		return items.get(position);
	}

	public long getItemId(int position) {
		return -1;
	}
}
